package com.authine.cloudpivot.web.api.secondopen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.secondopen.modules.CmCrTermsParamVO;
import com.authine.cloudpivot.web.api.secondopen.modules.MdmMoFseoVO;
import com.authine.cloudpivot.web.api.secondopen.modules.QadResultVO;
import com.authine.cloudpivot.web.api.secondopen.modules.ThsqParamsDTO;
import com.authine.cloudpivot.web.api.secondopen.service.SalesManagementService;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import io.jsonwebtoken.lang.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dw4443
 * @version V1.0
 * @description: DOTO
 * @date 2021/10/21 11:48
 */
@Service
public class SalesManagementServiceImpl implements SalesManagementService {

    private static final Logger log = LoggerFactory.getLogger(SalesManagementServiceImpl.class);

    @Autowired
    private HxConfig hxConfig;

    @Override
    public QadResultVO sendCmCrTerms(CmCrTermsParamVO vos) {
        String url = hxConfig.getQadurlheader();
        String token = hxConfig.getToken();
        String xdomain = hxConfig.getXdomain();
        String xcode = "MdmCmMstrPut";
        String result = null;

        //修改QAD客户支付周期及方式
        url=url+"MdmCmMstr/Put";
        HashMap<String, String> map = new HashMap<>();
        map.put("x-corp","");
        map.put("x-domain",xdomain);
        map.put("x-code",xcode);
        map.put("x-token",token);

        String s = JSON.toJSONString(vos);
        result = doPutHttpRequest(url,map,s);

        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO = new QadResultVO();

        if (StringUtils.isNotBlank(result)){
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");

            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;

    }

    @Override
    public QadResultVO returnApplication(ThsqParamsDTO thsqParamsDTO) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode=null;
        String xtoken = hxConfig.getToken();
        String result=null;
        QadResultVO qadResultVO=new QadResultVO();
        //退货至地点
        String thzdd = thsqParamsDTO.getThzdd();
        //当前系统时间
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = ft.format(now);

        List<Map<String, Object>> thqdList = thsqParamsDTO.getThqdList();

        //获取退货来源及退货账务处理信息，用于判断走哪个接口(MO移库单?销售订单?)
        String thly = thsqParamsDTO.getThly();
        String thzwclxx = thsqParamsDTO.getThzwclxx();

        if ("客户".equals(thly)&&"客户开具《红字增值税专用发票通知单》".equals(thzwclxx)){
            //走销售订单接口
            xcode="MdmSomtPost";
            url=url+"MdmSomt/Post";


            if (!Collections.isEmpty(thqdList)) {
                for (int i = 0; i < thqdList.size(); i++) {
                    //每个子表里的商品编码
                    String spbm = String.valueOf(thqdList.get(i).get("spbm"));
                    Integer thsl = (Integer) thqdList.get(i).get("thsl");
                    String dw = String.valueOf(thqdList.get(i).get("dw"));
                    Integer thdj = (Integer) thqdList.get(i).get("thdj");
                    thsqParamsDTO.setSpbm(spbm);
                    thsqParamsDTO.setThsl(thsl);
                    thsqParamsDTO.setDw(dw);
                    thsqParamsDTO.setThdj(thdj);
                }
            }

          //  result = HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,JSON.toJSONString(dysqParamVO));

        }else if (("第二方库位".equals(thly)||"第三方库位".equals(thly))&&"移库".equals(thzwclxx)){
            //MO移库单接口
            xcode="MdmMoFseoPost";
            url=url+"MdmMoFseo/Post";
            MdmMoFseoVO mdmMoFseoVO = new MdmMoFseoVO();
            mdmMoFseoVO.setMdmMoFseoNbr("1");
            if (thzdd.equals("THK退货库房")){
                mdmMoFseoVO.setMdmMoFseoEngCode("THK");
                mdmMoFseoVO.setMdmMoFseoShipto("THK");
            }else if(thzdd.equals("SB三包退货库")){
                mdmMoFseoVO.setMdmMoFseoEngCode("SB");
                mdmMoFseoVO.setMdmMoFseoShipto("SB");
            }
            mdmMoFseoVO.setMdmMoFseoOrdDate(nowTime);
            mdmMoFseoVO.setMdmMoFseoReqDate(nowTime);
            mdmMoFseoVO.setMdmMoFseoDueDate(ft.format(thsqParamsDTO.getEndtime()));
            mdmMoFseoVO.setMdmMoFseoRmks(thsqParamsDTO.getThms());
            mdmMoFseoVO.setMdmMoFseoSite(thsqParamsDTO.getSite());
            mdmMoFseoVO.setMdmMoFseoSodLoc(thsqParamsDTO.getLoc());
            mdmMoFseoVO.setMdmMoFseoConfirm(true);
            mdmMoFseoVO.setMdmMoFseoCurr("RMB");
            if (!Collections.isEmpty(thqdList)) {
                for (int i = 0; i < thqdList.size(); i++) {
                    //每个子表里的商品编码
                    String spbm = String.valueOf(thqdList.get(i).get("spbm"));
                    BigDecimal thsl = (BigDecimal) thqdList.get(i).get("thsl");
                    mdmMoFseoVO.setMdmMoFseoSodPart(spbm);
                    mdmMoFseoVO.setMdmMoFseoSodQtyOrd(thsl);
                }
            }

            result = HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,JSON.toJSONString(mdmMoFseoVO));

        }else{
            //回传报错信息

        }
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);

        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));

        } else {
            log.info("退货清单子表数据为空，无法完成退货操作");
        }

        return qadResultVO;

    }


    //httpput请求方法
    public String doPutHttpRequest(String url, Map<String, String> headerMap, String requestBody) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            HttpPut post = new HttpPut(url);
            //添加头部信息
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                post.addHeader(header.getKey(), header.getValue());
            }
            HttpEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            System.out.println("请求体是："+requestBody);
            post.setEntity(entity);
            response = httpClient.execute(post);
            // 获得响应的实体对象
            HttpEntity httpEntity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println("PUT请求路径："+post);
            System.out.println("PUT请求结果："+entityStr);
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        }
        return entityStr;
    }
}
